package com.nitramf.catchmystream.services.sync;

import com.nitramf.catchmystream.entities.Item;
import com.nitramf.catchmystream.entities.RssFeed;
import com.nitramf.catchmystream.services.crud.CrudService;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Asynchronous;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.Schedule;

/**
 * Process RSS feeds
 * @author martinfilliau
 */
@Stateless
@LocalBean
public class RssSyncService {

    @EJB
    private CrudService crud;

    @Schedule(hour = "*", minute = "*/15")
    public void sync() {
        List<RssFeed> feeds = crud.findWithNamedQuery(RssFeed.QUERY_GET_ALL_ACTIVATED);
        for (RssFeed feed : feeds) {
            try {
                processFeed(feed);
            }
            catch (Exception ex) {
                Logger.getLogger(RssSyncService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Asynchronous
    private void processFeed(RssFeed f) throws MalformedURLException, IOException, IllegalArgumentException, FeedException, FetcherException {
        URL feedSource = new URL(f.getUri());
        FeedFetcher fetcher = new HttpURLFeedFetcher();
        String userAgent = "catchmystream/0.1";
        fetcher.setUserAgent(userAgent);
        SyndFeed feed = fetcher.retrieveFeed(feedSource);

        List<SyndEntry> entries = feed.getEntries();
        Item i;
        for (SyndEntry entry : entries) {
            String content = "";        // main content

            i = new Item();
            i.setAuthor(entry.getAuthor());
            i.setPublishedDate(entry.getPublishedDate());
            i.setiAmTheAuthor(f.isiAmTheAuthor());
            //i.setSource(f.getn);
            i.setTitle(entry.getTitle());
            i.setUri(entry.getLink());

            if (entry.getDescription() != null) {
                content = entry.getDescription().getValue();
            }

            List<SyndContentImpl> contents = entry.getContents();

            if (contents.size() >= 1) {
                if (content.length() == 0) {
                    content = contents.get(0).getValue();
                } else {
                    content += " " + contents.get(0).getValue();
                }
            }

            i.setDescription(content);
            /*
            List<String> tags = new ArrayList<String>();
            List<SyndCategory> categories = entry.getCategories();
            for (SyndCategory category : categories) {
            tags.add(category.getName());
            }

            if (!tags.isEmpty()) {
            i.setKeywords(tags);
            }

            service.sendToSolr(i);
            i = null;
             */
        }

    }
}
